package com.xauto.pioneer.appuser.activity.mine.balance;

import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.activity.common.PayUtil;
import com.xauto.pioneer.appuser.adapter.PaymentAdapter;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.MemberCallBack;
import com.xauto.pioneer.appuser.model.BalanceOrderInfo;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.Member;
import com.xauto.pioneer.appuser.model.Payment;
import com.xauto.pioneer.appuser.util.CashierInputFilter;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.view.TopBar;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/***
 * 账户充值 页面
 * @author Lemon Tue 7 Mar 17:24
 */
public class AccountTopUpActivity extends BaseActivity {

    @Bind(R.id.topBar) TopBar topBar;
    @Bind(R.id.etAccountTopUpCost) EditText etTopUpCost;
    @Bind(R.id.listPayment)
    ListView listPayment;
    /** 支付方式适配器*/
    private PaymentAdapter paymentAdapter;
    private String paymentCode = Constants.PAY_TYPE_WECHAT;

    int accountnum;
    @Override
    protected int getContentView() {
        return R.layout.ac_account_top_up;
    }

    @Override
    protected void initView() {
        //注册EventBus
        EventBus.getDefault().register(this);
        topBar.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE);
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setText(TopBar.TITLE, R.string.account_top_up);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        listPayment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(!paymentAdapter.getDataList().get(position).isChoose) {
                    for (int i = 0; i < paymentAdapter.getDataList().size(); i++) {
                        paymentAdapter.getDataList().get(i).isChoose = false;
                    }
                    paymentAdapter.getDataList().get(position).isChoose = true;
                    paymentAdapter.notifyDataSetChanged();
                    paymentCode = paymentAdapter.getDataList().get(position).getPayment_code();
                }
            }
        });
        //输入金额拦截
        InputFilter[] inputFilters = {new CashierInputFilter()};
        etTopUpCost.setFilters(inputFilters);

    }

    @Override
    protected void initData() {
        accountnum = getIntent().getIntExtra("accountnum",0);
        Log.e("tag","num = " + accountnum);
        etTopUpCost.setHint("最小充值金额"+accountnum);
        paymentAdapter = new PaymentAdapter(this, R.layout.item_payment);
        listPayment.setAdapter(paymentAdapter);
        List<Payment> payments = new Payment().getPaymentListForOnLine(mContext);
        paymentAdapter.getDataList().addAll(payments);
        paymentAdapter.notifyDataSetChanged();
    }


    @OnClick({ R.id.tvAccountTopUpConfirmPay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvAccountTopUpConfirmPay:
                //确认支付
                for (int i = 0; i < paymentAdapter.getDataList().size(); i++) {
                    if(paymentAdapter.getDataList().get(i).isChoose) {
                        paymentCode = paymentAdapter.getDataList().get(i).getPayment_code();
                    }
                }
                balanceRecharge();
                break;
        }
    }

    /**
     * 余额充值 STEP 1
     */
    private void balanceRecharge(){
       String money =  etTopUpCost.getText().toString().trim();
        Double douMoney = 0d;
        try {
            douMoney = Double.parseDouble(money);
        }catch (Exception e){

        }
        if (douMoney == 0){
            prompt("充值金额不能为空");
            return;
        }
        new LHttpLib().addBalanceOrder(mContext, memberId,money, paymentCode, new BaseLHttpHandler(mContext, true, true) {

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                BalanceOrderInfo balanceOrderInfo = new BalanceOrderInfo().parse(jsonStatus.data.optJSONObject("balance_order_info"));
                submitBalanceOrder(balanceOrderInfo);
            }
        });

    }

    /**
     * 余额充值 STEP 2
     */
    private void submitBalanceOrder(BalanceOrderInfo balanceOrderInfo){
        new LHttpLib().submitBalanceOrder(mContext, memberId,balanceOrderInfo.balance_order_no, new BaseLHttpHandler(mContext, true, true) {

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                String payment_order_param = jsonStatus.data.optString("payment_order_param");
                String payment_order_url = jsonStatus.data.optString("payment_order_url");
                new PayUtil(AccountTopUpActivity.this, payment_order_param,paymentCode);
            }
        });
    }

    /**
     * 充值成功
     */
    private void  rechargeSuccess(){
        // TODO: 2017/6/8
        prompt("余额充值成功");
        //刷新数据
        DataLoadUtil.refreshMemberData(mContext, new MemberCallBack() {
            @Override
            public void getMember(Member member) {
                finish();
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册EventBus
        EventBus.getDefault().unregister(this);
    }
    /**
     * 接受支付成功的通知信息
     * @param paymentCode
     */
    public void onEventMainThread(String paymentCode){
        switch (paymentCode){
            //支付宝支付成功
            case Constants.PAY_TYPE_ALIPAY:
                rechargeSuccess();
                break;
            //微信支付成功
            case Constants.PAY_TYPE_WECHAT:
                rechargeSuccess();
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if(Constants.IS_WX_PAY) {
            Constants.IS_WX_PAY = false;
            if(Constants.WX_PAY_RESULTCODE.equals("-1")) {
                //支付失败
                prompt("支付失败，请重试");
            } else if(Constants.WX_PAY_RESULTCODE.equals("-2")) {
                //取消支付
                prompt("您取消了支付，如有疑问请联系客服");
            } else {
                //微信支付返回
                EventBus.getDefault().post(Constants.PAY_TYPE_WECHAT);//支付成功后调用服务器，获取支付成功｜失败
            }
        }
    }
}
